package controller

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"learn-gin/app/models"
	"learn-gin/global"
	"learn-gin/utils"
	"math"
	"net/http"
)

var (
	log  = global.SUGAREDLOGGER
	db   = global.EWA_DB
	User = new(userCtrl)
)

type userCtrl struct{}

func (c *userCtrl) Save(ctx *gin.Context) {
	//var req *models.User

	//if err := ctx.ShouldBind(&req); err != nil {
	//	ctx.JSON(-1, gin.H{
	//		"message": "req err",
	//	})
	//	return
	//}
	json_byte, _ := ctx.GetRawData()
	var m map[string]interface{}
	err := json.Unmarshal(json_byte, &m)
	if err != nil {
		return
	}
	req := new(models.User)
	req.Name = m["name"].(string)
	log.Infof("req=%+v", req)
	if err := db.Model(models.User{}).Save(req).Error; err != nil {
		ctx.JSON(-1, gin.H{
			"message": err.Error(),
		})
		return
	}

	// 返回结果
	ctx.JSON(http.StatusOK, gin.H{
		"message": "ok",
		"data":    req.Id,
	})
}
func (c *userCtrl) List(ctx *gin.Context) {

	//var user models.User
	var pager utils.Pager
	var users []models.User
	// 参数
	var req *utils.UserPageReq
	if err := ctx.ShouldBind(&req); err != nil {
		ctx.JSON(-1, gin.H{
			"message": "req err",
		})
		return
	}

	log.Infof("req=%+v", req)
	var total int64
	query := db.Model(models.User{})
	if req != nil {
		if req.Name != "" {
			//user.Name = req.Name
			query = query.Where("name like ?", "%"+req.Name+"%")
		}
	}
	query = query.Order("id desc")
	if err := query.Scopes(utils.Paginate(req.PageReq)).Find(&users).Count(&total).Error; err != nil {
		ctx.JSON(-1, gin.H{
			"message": "err",
		})
		return
	}

	pager.Data = users
	pager.PageSize = req.PageReq.PageSize
	pager.TotalPages = int64(math.Ceil(float64(total) / float64(req.PageReq.PageSize)))
	pager.Count = total
	pager.CurrentPage = req.PageReq.Page
	// 返回结果
	ctx.JSON(http.StatusOK, gin.H{
		"message": "ok",
		"data":    pager,
	})
}

func (c *userCtrl) Detail(ctx *gin.Context) {
	log.Infof("ctx=%+v", ctx)
	var Result models.User
	id := ctx.Query("id")
	db.Debug().Where("id = ?", id).Find(&Result)
	ctx.JSON(200, gin.H{
		"data": Result,
	})
}
